package net.com.sunkey.messagehandler;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map.Entry;

import net.com.sunkey.protobuf.Protocol;
import net.com.sunkey.protobuf.UserData;
import net.com.sunkey.protobuf.UserListResponse.UserListResponseData;
import net.com.sunkey.serverlogic.Room;
import net.com.sunkey.serverlogic.Server;
import net.com.sunkey.serverlogic.User;

/**
 * @author kohachiro
 *
 */
public class UserListResponseHandler {
	/* (non-Javadoc)
	 * @see com.sunkey.tdserver.messagehandler.MessageHandler#invoke(java.lang.Object, org.jboss.netty.channel.Channel)
	 */
	//@Override
	public static int invoke(Object data, Object channel) throws Exception {
		System.out.println("["+channel.hashCode()+"]["+ Protocol.MessageHandler.UserListResponse_VALUE+"]UserListResponse");	
		UserListResponseData.Builder builder=UserListResponseData.newBuilder();
		User user;
		for (Iterator<Entry<Integer, User>> er = ((Room)data).getUserList().entrySet().iterator();er.hasNext();){
			user=er.next().getValue();
			UserData.User.Builder userBuilder=UserData.User.newBuilder();
			userBuilder.setId(user.getId());
			userBuilder.setName(user.getName());
			
			user.addProperties(userBuilder);
			
			builder.addUser(userBuilder);	
		}
		UserListResponseData message=builder.build();
		
		Server.sendResponse(Protocol.MessageHandler.UserListResponse_VALUE,ByteBuffer.wrap(message.toByteArray()), channel);
		return Protocol.MessageHandler.UserListResponse_VALUE;
	}

}
